# coding:utf-8
import logging
from logging import FileHandler, StreamHandler, Formatter
__name__ = 'logger'

"""

# 本代码只支持写入在指定的同一个日志文件中

# set message with the specified log level
Logger.init_logger()

Logger.debug(message)
Logger.info(message)
Logger.warning(message)
Logger.error(message)
Logger.critical(message)
"""


class Logger:
    log = None

    @classmethod
    def init_logger(cls, filename='file.log', mode='a', encoding='gb2312', delay=None, log_level=4):
        """

        初始化一个logger，既能输出也能写入日志文件
        log_level优先级：0最大，4最小

        :param filename: 设置文件名
        :param mode: 设置文件读写模式
        :param encoding: 设置编码格式
        :param delay: 设置延迟
        :param log_level: 默认为debug级别 共0 1 2 3 4种级别
        :return:
        """
        # 设置一个log_level
        level = (
            logging.CRITICAL,
            logging.ERROR,
            logging.WARNING,
            logging.INFO,
            logging.DEBUG,
        )
        # Return a logger with the specified name
        log = logging.getLogger(__name__)
        log.setLevel(level[log_level])

        # 初始化处理程序
        # mode默认位追加模式
        handler_file = FileHandler(filename=filename, mode=mode, encoding=encoding, delay=delay)
        handler_stream = StreamHandler()

        # 这里设置的debug/
        handler_file.setLevel(logging.DEBUG)
        handler_stream.setLevel(logging.DEBUG)

        # 设置日志格式
        # 默认：'%(asctime)s [%(name)s] %(levelname)s: %(message)s'
        format = Formatter('%(asctime)s|[%(name)s]|%(levelname)s: %(message)s')
        handler_file.setFormatter(format)
        handler_stream.setFormatter(format)

        # log添加这些handler设置
        log.addHandler(handler_file)
        log.addHandler(handler_stream)

        # 初始化cls.log
        cls.log = log

    @classmethod
    def debug(cls, message):
        cls.log.debug(message)

    @classmethod
    def info(cls, message):
        cls.log.info(message)

    @classmethod
    def warning(cls, message):
        cls.log.warning(message)

    @classmethod
    def error(cls, message):
        cls.log.error(message)

    @classmethod
    def critical(cls, message):
        cls.log.critical(message)
